package csc.training.jsf2.common;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

public class CellPhoneConvertor implements Converter{

	public Object getAsObject(FacesContext arg0, UIComponent arg1, String value) throws ConverterException{
		// No need implement because just display only as String       
		return null;
	}

	public String getAsString(FacesContext arg0, UIComponent arg1, Object value) throws ConverterException{
	 String inputVal = null;
        if (value == null) {
            return null;
        }
        try {
            inputVal = (String) value;            
            return formatCellPhone(inputVal);
            
        } catch (Exception e) {
            FacesMessage errMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"CellPone conversion error",e.getMessage());
            throw new ConverterException(errMsg.getSummary());
        }
	}
	
	private String formatCellPhone(String value){
		char[] input = value.toCharArray();
        StringBuffer buffer = new StringBuffer(15);
        buffer.append("+84 ");
        for(int i=0; i<input.length-1;i++){
        	if ((i % 3) == 0 && i != 0) {
        		buffer.append(" ");
        	}
        	buffer.append(input[i+1]);
        }
        return buffer.toString();
	}
	

}
